import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class CSVUtils {

  //Load records from the specified file path.
  public static int load(String filename, List<Contact> contactList) {
    int nLine = 0; //Number of lines
    Path pathToFile = Paths.get(filename);

    // create an instance of BufferedReader
    // using try with resource, Java 7 feature to close resources
    try (BufferedReader br = Files.newBufferedReader(pathToFile,
        StandardCharsets.US_ASCII)) {
      // read the first line from the text file
      String line = br.readLine();

      // loop until all lines are read
      while (line != null && !line.isEmpty()) {
        // use string.split to load a string array with the values from
        // each line of the file, using a comma as the delimiter
        String[] arrLine = line.split(",");

        if (arrLine.length
            >= 1) {  //At least, the line should have one item (the first column is name)
          //For demonstration purpose, I'm just printing the loaded row here.
          //But you are supposed to load the obtained fields into a Contact object.
          Contact contact = Contact.formatContact(arrLine);
          contactList.add(contact);
          nLine++;
        }
        // read next line before looping
        // if end of file reached, line would be null
        line = br.readLine();
      }
    } catch (IOException ioe) {
      nLine = -1;  //Return -1, indicating error
    }
    return nLine;  //Return total number of records loaded
  }

  //Load records from the specified file path.
  public static int loadOrder(String filename, List<Order> orderList) {
    int nLine = 0; //Number of lines
    Path pathToFile = Paths.get(filename);

    // create an instance of BufferedReader
    // using try with resource, Java 7 feature to close resources
    try (BufferedReader br = Files.newBufferedReader(pathToFile,
        StandardCharsets.US_ASCII)) {
      // read the first line from the text file
      String line = br.readLine();

      // loop until all lines are read
      while (line != null && !line.isEmpty()) {
        // use string.split to load a string array with the values from
        // each line of the file, using a comma as the delimiter
        String[] arrLine = line.split(",");

        if (arrLine.length >= 1) {
          Order order = new Order();
          order.setOrderID(Integer.parseInt(arrLine[0]));
          order.setCustomerName(arrLine[1]);
          order.setProductName(arrLine[2]);
          order.setQuantity(Integer.parseInt(arrLine[3]));
          orderList.add(order);
          nLine++;
        }
        // read next line before looping
        // if end of file reached, line would be null
        line = br.readLine();
      }
    } catch (IOException ioe) {
      nLine = -1;  //Return -1, indicating error
    }
    return nLine;  //Return total number of records loaded
  }

  // save into the file with the given name
  public static int saveAs(String filename, List<Contact> contacts) {
    int nLine = 0;
    BufferedWriter bufferedWriter = null;
    try {
      File file = new File(filename);
      //This is to write into a new file.
      //To "append" more data to the existing file, you may:
      //File file = new File(filePath,true);

      //if file doesn't exists, then create it
      if (!file.exists()) {
        file.createNewFile();
      }

      FileWriter fileWriter = new FileWriter(file);
      bufferedWriter = new BufferedWriter(fileWriter);

      //For demonstration purpose, the lines are given directly as string literals in the array.
      //You are expected to write the information of all contacts in your AddressBook into the file.
      for (Contact contact : contacts) {
        Field[] fields = contact.getClass().getDeclaredFields();
        StringBuilder sb = new StringBuilder();
        for (Field field : fields) {
          field.setAccessible(true);
          try {
            if (null != field.get(contact)) {
              sb.append(field.get(contact)).append(",");
            }
          } catch (IllegalAccessException e) {
            e.printStackTrace();
          }
        }
        bufferedWriter.write(sb.toString());
        bufferedWriter.newLine();
        nLine++;
      }
    } catch (IOException e) {
      nLine = -1;  //Something went wrong.

    } finally {
      try {
        if (bufferedWriter != null) {
          bufferedWriter.close();
        }
      } catch (IOException ex) {
        nLine = -1; //Oops again.
      }
    }
    return nLine; //Return total number of records/lines saved
  }
}